<template>
  <div>
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>部门管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-form :inline="true" :model="deptVo" class="demo-form-inline">
        <el-form-item label="部门名称" label-width="70px">
          <el-input clearable v-model="deptVo.name" placeholder="请输入部门名称"></el-input>
        </el-form-item>
        <el-form-item label="手机号" label-width="70px">
          <el-input clearable v-model="deptVo.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item style="margin-left: 10px">
          <el-button icon="el-icon-refresh" @click="resetDeptVo">重置</el-button>
          <el-button type="primary" icon="el-icon-search" @click="getDeptList">查询</el-button>
          <el-button type="success" icon="el-icon-plus" @click="show">添加</el-button>
        </el-form-item>
      </el-form>

      <!--表格-->
      <el-table
        :data="deptList"
        border
        max-height="100%"
        style="width: 100%;">
        <el-table-column
          prop="name"
          label="部门名称"
          width="300">
        </el-table-column>
        <el-table-column
          prop="phone"
          label="手机号"
          width="200">
        </el-table-column>
        <el-table-column
          prop="address"
          label="地址"
          width="600">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scop">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="edit(scop.row)"></el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="del(scop.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="padding-top: 15px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"

        :current-page="current"
        :page-sizes="[6, 10, 20, 30,60]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

      <!-- 添加对话框 -->
      <el-dialog :title="formTitle === 'add' ? '添加部门' : '编辑部门'" :visible.sync="addDialogVisible" width="50%" @close="editClose">
        <span>
          <el-form
            :model="editForm"
            :label-position="labelPosition"
            :rules="addFormRules"
            ref="editFormRef"
            label-width="80px"
          >
            <el-row>
              <el-col :span="15">
                <div class="grid-content bg-purple">
                  <el-form-item label="部门名称" prop="name">
                    <el-input v-model="editForm.name" clearable></el-input>
                  </el-form-item>
                </div>
              </el-col>
               <el-col :span="15">
                <div class="grid-content bg-purple">
                  <el-form-item label="联系方式" prop="phone">
                    <el-input v-model="editForm.phone" clearable></el-input>
                  </el-form-item>
                </div>
              </el-col>
                <el-col :span="15">
                <div class="grid-content bg-purple">
                  <el-form-item label="办公地址" prop="address">
                    <el-input v-model="editForm.address" clearable></el-input>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </span>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="addDept"
            :loading="btnLoading"
            :disabled="btnDisabled"
          >确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { addDept, deleteDeprById, findDeptPage, updataDepat } from '@/api/dept'

export default {
  name: 'Departments',
  data(){
    //手机号检验规则
    var checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[34578]\d{9}$$/;
      if (!value) {
        return callback(new Error("电话号码不能为空"));
      }
      setTimeout(() => {
        // Number.isInteger是es6验证数字是否为整数的方法,实际输入的数字总是识别成字符串
        // 所以在前面加了一个+实现隐式转换

        if (!Number.isInteger(+value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (phoneReg.test(value)) {
            callback();
          } else {
            callback(new Error("电话号码格式不正确"));
          }
        }
      }, 100);
    };
    return {
      deptVo: {
        name: "",
        phone: ""
      },
      deptList :[],
      //每页显示的条数
      size: 6,
      //总条数
      total: 100,
      //当前页码
      current: 1,
      addDialogVisible:false,   //添加对话框
      editForm: {},
      labelPosition: "right",  //lable对齐方式
      btnLoading: false,
      btnDisabled: false,
      addFormRules: {
        name: [
          { required: true, message: "请输入部门名称", trigger: "blur" },
          { min: 1, max: 20, message: "长度不能超过 20 个字符", trigger: "blur" }
        ],
        phone: [
          {
            required: true,
            validator: checkPhone,
            trigger: "blur"
          }
        ],
        address: [
          { required: false, message: "请输入角色描述", trigger: "blur" },
          { min: 1, max: 20, message: "长度不能超过 20 个字符", trigger: "blur" }
        ]
      }, //添加表单验证规则
      formTitle :'',
    };
  },
  mounted () {
    this.getDeptList();
  },
  methods:{
    //当每页条数改变的时候
    handleSizeChange (val) {
      //将val赋值到size
      this.size = val;
      //重新到后台查询
      this.getDeptList();
    },
    //当前页码改变的时候
    handleCurrentChange (val) {
      this.current=val;
      this.getDeptList();
    },
    async getDeptList(){
      const {data} =await  findDeptPage(this.current,this.size,this.deptVo)
      this.deptList=data.data.records;
      this.total=data.data.total;
    },
    //重置
    resetDeptVo(){
      this.deptVo.name=""
      this.deptVo.phone=""
      this.getDeptList()
    },
    // 按钮点击事件 显示新增编辑弹窗组件
    show(){
      this.formTitle ='add',
      this.addDialogVisible = true
    },
    /**
     * 关闭编辑弹出框
     */
    editClose() {
      this.$refs.editFormRef.clearValidate();
      this.editForm = {};
    },
    /**
     * 添加部门/编辑部门
     * @returns {Promise<void>}
     */
    async addDept(){
      this.$refs.editFormRef.validate(async valid =>{
        if (!valid){
          return;
        }else {
          this.btnLoading = true;
          this.btnDisabled = true;
          //从缓存中获取用户id
          var userInfo=sessionStorage.getItem("userInfo")
          this.editForm.mgrId=JSON.parse(userInfo).userInfoVO.id
          if (this.formTitle =="add"){
            const { data: res} =await addDept(this.editForm)
            if (res.code=='200'){
              this.$notify.success({
                title: '操作成功',
                message: '部门添加成功',
              })
              this.editForm = {};
              this.getDeptList();
            }else {
              this.$message.error(res.message);
            }
          }else {
            this.editForm.createTime=''
            this.editForm.modifiedTime=''
            const {data: res} =await updataDepat(this.editForm)
            if (res.code=='200'){
              this.$notify.success({
                title: '操作成功',
                message: '部门修改成功',
              })
              this.editForm = {};
              this.getDeptList();
            }else {
              this.$message.error(res.message);
            }
          }

          this.addDialogVisible = false;
          this.btnLoading = false;
          this.btnDisabled = false;
        }
      });
    },
    /**
     * 部门详情
     * @param row
     * @returns {Promise<void>}
     */
    async edit(row){
      this.formTitle ='edit';
      this.editForm=row;
      this.addDialogVisible = true;
    },
    /***
     * 删除部门
     * @param id
     * @returns {Promise<void>}
     */
    async del(id){
      var res = await this.$confirm(
        "此操作将永久删除该部门, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
      if (res == "confirm"){
        const { data: res } =await deleteDeprById(id)
        if (res.code == 200) {
          this.$notify.success({
            title:'操作成功',
            message:'部门删除成功',
          });
          this.getDeptList();
        } else {
          this.$message.error(res.message);
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>

</style>
